package it.unicam.cs.cosy.bioshape.core.collisiondetection.broadphase;

import it.unicam.cs.cosy.bioshape.core.components.Entity;
import it.unicam.cs.cosy.bioshape.core.components.EntityPair;
import it.unicam.cs.cosy.bioshape.core.components.WallEntity;
import java.util.ArrayList;
import java.util.List;

/**
 * Brute force implementation of the {@link BroadPhase} interface. The algorithm
 * is based on direct confrontation of <i>all</i> the entities in the simulation
 * against each other. The confrontation is only done between each entity and
 * the subsequent ones in the list of all entities. This gives a number of
 * confrontations equal to {@code n*(n-1) / 2} with {@code n} number of entities
 * in the list. The worst-case performance of this approach is <i>O(n^2)</i>.
 * 
 * @author Matteo Micheletti, Federico Buti
 */
public class BruteForceBroadPhase implements BroadPhase {

	List<Entity> entities;

	/**
	 * Builds the
	 * 
	 * @param list
	 *            entities to be checked for collisions
	 */
	public BruteForceBroadPhase(List<Entity> list) {
		this.entities = list;
	}

	/**
	 * Realizes the whole BroadPhase, through the following steps:<br>
	 * <ol>
	 * <li>Selection of the neighbourhood entities;
	 * <li>Eulero principle application on them.
	 * </ol>
	 * 
	 * Entities which are not shaped are discarded from the control
	 * 
	 * @return string the obtained data.
	 */
	@Override
	public ArrayList<EntityPair> getOverlappingPairs() {
		ArrayList<EntityPair> pairs = new ArrayList<EntityPair>();
		for (int i = 0; i < entities.size(); i++) {
			for (int j = i + 1; j < entities.size(); j++) {
				Entity e1, e2;
				e1 = entities.get(i);
				e2 = entities.get(j);
				if (e1 instanceof WallEntity && e2 instanceof WallEntity)
					continue;
				// check
				if (e1.getBounds().intersect(e2.getBounds())) {
					// e1.addCollisionEntity(e2);
					pairs.add(new EntityPair(e1, e2));
				}
			}
		}
		return pairs;
	}
}
